﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Collections.Specialized;

namespace HttpUploader5.demoAccess.db
{
	public partial class ajax_create_fid : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			string md5 = Request.Form["md5"];
			string uid = Request.Form["uid"];
			string fileLength = Request.Form["fileLength"];
			string fileSize = Request.Form["fileSize"];
			//客户端使用的是encodeURIComponent编码，
			string pathLocal = HttpUtility.UrlDecode(Request.Form["pathLocal"]);//utf-8解码
			string json = "0";

			//参数为空
			if (string.IsNullOrEmpty(md5)
				|| string.IsNullOrEmpty(uid)
				|| string.IsNullOrEmpty(fileSize))
			{
				Response.Write("param is null\n");
				return;
			}

			HttpUploaderDB db = new HttpUploaderDB();
			xdb_files inf = new xdb_files();
			inf.FileNameLocal = Path.GetFileName(pathLocal);
			inf.FilePathLocal = pathLocal;
			//以MD5方式命名
			inf.FileNameRemote = md5 + Path.GetExtension(pathLocal).ToLower();
			//以原始文件命名
			//inf.FileNameRemote = inf.FileNameLocal;

			//数据库存在相同文件
			if ( db.GetFileInfByMd5(md5, ref inf) )
			{
				inf.FileNameLocal = Path.GetFileName(pathLocal);
				inf.FilePathLocal = pathLocal;
				inf.uid = int.Parse(uid);//将当前文件UID设置为当前用户UID
				inf.IsDeleted = false;
				inf.fid = db.Add(ref inf);
			}//数据库不存在相同文件
			else
			{
				HttpUploaderCfg cfg = new HttpUploaderCfg();
				cfg.CreateUploadPath();

				inf.uid = int.Parse(uid);//将当前文件UID设置为当前用户UID
				inf.FileSize = fileSize;
				inf.FileMD5 = md5;
				inf.FileLength = Convert.ToInt32(fileLength);
				inf.FilePathRemote = Path.Combine(cfg.GetUploadPath(),inf.FileNameRemote);
				inf.FilePathRelative = Path.Combine(cfg.GetRelatPath(),inf.FileNameRemote);
				inf.fid = db.Add(ref inf);
			}
			json = inf.ToJson();
			Response.Write(json);
		}
	}
}